<template>
  <div>
    <el-row>
      <div style="display: flex; align-items: center; margin-bottom: 15px">
        <div style="flex: 1">
          sku:{{ info.skuNo }}
          <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(info.skuNo)"></i>
        </div>
        <div style="flex: 1">
          库位号:{{ info.stockPositionNo }}
          <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(info.stockPositionNo)"></i>
        </div>
      </div>
    </el-row>
    <el-row>
      <div>
        <el-select
          @change="setTemplateInfo"
          style="margin-right: 15px"
          size="mini"
          v-model="selectedTemplate"
          :placeholder="$t('请选择')"
        >
          <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button size="mini" type="primary" @click="handleAddTemplate" v-if="!disabled"> 新增模板 </el-button>
        <el-button
          size="mini"
          type="success"
          @click="handleCopySelectedTemplate"
          v-if="selectedTemplate"
          v-hasPermi="['distribution:sku:skuTempCopy']"
        >
          复制当前模板
        </el-button>
      </div>
    </el-row>
    <el-form
      v-if="type"
      ref="formRef"
      :model="form"
      :disabled="disabled"
      :rules="rules"
      label-width="90px"
      style="margin-top: 10px"
    >
      <el-row :gutter="2">
        <el-col :span="4">
          <el-form-item label="sku:" label-width="60px" prop="skuNameJp">
            {{ info.skuNo }}
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="模板名称:" prop="name">
            <el-input v-model="form.name" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="平台sku:" prop="skuNo">
            <el-input v-model="form.skuNo" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="价格(JPY):" prop="price">
            <el-input
              size="mini"
              v-model="form.price"
              oninput="value=value.replace(/[^\d.]/g, '')"
              controls-position="right"
              :min="0"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="标题:" prop="title">
            <el-input v-model="form.title" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="10">
          <!-- 五点描述 -->
          <div class="des-title">五点描述</div>
          <el-descriptions :column="1" border class="des-desc5">
            <el-descriptions-item label="描述1" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc1">
                <el-input v-model="form.desc1" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述2" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc2">
                <el-input v-model="form.desc2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述3" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc3">
                <el-input v-model="form.desc3" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述4" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc4">
                <el-input v-model="form.desc4" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述5" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc5">
                <el-input v-model="form.desc5" />
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="10">
          <!-- 详细描述 -->
          <div class="des-title">详细描述</div>
          <div class="des-detail">
            <div class="des-detail_left">详情</div>
            <div class="des-detail_right">
              <el-form-item label-width="0" prop="descDetails">
                <el-input
                  style="height: 100%"
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="form.descDetails"
                  :rows="10"
                />
              </el-form-item>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div v-show="type == 'edit'">
            <el-button
              type="danger"
              size="mini"
              @click="deleteTemplate"
              v-hasPermi="['distribution:skuDistributor:deleteDistributorSkuTemplate']"
              v-show="selectedTemplate"
            >
              删除模板
            </el-button>
          </div>
          <div v-show="type == 'add'">
            <el-button
              v-hasPermi="['distribution:skuDistributor:insertDistributorSkuTemplate']"
              type="success"
              style="margin-left: 10px"
              @click="addTemplate"
            >
              确认新增
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div style="padding: 10px 0">模板图片</div>
      <el-row>
        <div class="template-img" :style="disabled ? 'pointer-events: none;' : ''">
          <ImgUploadManage
            :businessId="form.id"
            type="3"
            :limit="10"
            :uploadLimit="10"
            :fileList.sync="form.distributorSkuTemplateImgList"
          />
        </div>
      </el-row>
    </el-form>
    <div style="text-align: right; margin-top: 30px">
      <el-button type="primary" @click="handleEdit" v-if="!disabled && type != 'add' && selectedTemplate">
        修改模板
      </el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>

    <el-dialog
      width="500"
      :title="$t('复制模板')"
      destroy-on-close
      append-to-body
      :visible.sync="copySelectedTemplate.show"
      :before-close="() => (copySelectedTemplate.show = false)"
    >
      <el-form
        label-width="120px"
        @submit.native.prevent
        ref="copySelectedTemplateRef"
        :model="copySelectedTemplate.form"
        :rules="copySelectedTemplate.rules"
      >
        <el-form-item :label="$t('复制的模板名称')" prop="templateName">
          <el-input v-model="copySelectedTemplate.form.templateName" :placeholder="$t('请输入')" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleCopySelectedTemplateSubmit" type="primary">{{ $t('确认') }}</el-button>
        <el-button @click="copySelectedTemplate.show = false">{{ $t('关闭') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTemplate,
  deleteTemplate,
  editTemplate,
  getTemplateList,
  skuTempCopy,
} from '@/api/distribution/sku/skuInformation'
import draggable from 'vuedraggable'

export default {
  name: 'ErpDistributionSystemPlusSkuInformation',
  components: { draggable },

  props: {
    skuId: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      copySelectedTemplate: {
        show: false,
        form: {
          templateName: '',
        },
        rules: {
          templateName: [{ required: true, message: this.$t('请输入'), trigger: 'blur' }],
        },
      },
      isShowDialog: false,
      waitUploadList: [],
      uploadFlag: false,
      info: { skuNo: '', stockPositionNo: '' },
      backFormDate: {},
      selectedTemplate: '',
      /**模式 */
      type: '',
      form: {
        id: '',
        skuId: '',
        skuNo: '',
        /**模板名称 */
        name: '',
        /**价格(JPY) */
        price: '',
        /**标题 */
        title: '',
        /**描述1 */
        desc1: '',
        /**描述2 */
        desc2: '',
        /**描述3 */
        desc3: '',
        /**描述4 */
        desc4: '',
        /**描述5 */
        desc5: '',
        /**详情 */
        descDetails: '',
        /**模板图片 */
        distributorSkuTemplateImgList: '',
      },
      rules: {
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        // skuNo: [{ required: true, message: '请输入', trigger: 'blur' }],
        // price: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        combinationSku: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ validator: this.validLength, required: true, trigger: 'change' }],
        desc1: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc2: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc3: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc4: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc5: [{ validator: this.validLength, required: false, trigger: 'change' }],
        descDetails: [{ validator: this.validLength, required: false, trigger: 'change' }],
      },
      templateList: [],
    }
  },
  created() {
    this.resetForm()
    this.getList(true)
  },
  watch: {
    skuId: function (newValue) {
      this.form.skuId = newValue
      this.getList(true)
    },
  },
  mounted() {
    this.form.skuId = this.skuId
  },

  methods: {
    handleCopySelectedTemplateSubmit() {
      this.$refs['copySelectedTemplateRef'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.selectedTemplate,
            // type	类型 1-sku 2-组合
            type: 1,
            name: this.copySelectedTemplate.form.templateName,
          }
          skuTempCopy(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.getList()
              this.copySelectedTemplate.show = false
            }
          })
        }
      })
    },
    handleCopySelectedTemplate() {
      this.copySelectedTemplate.show = true
      this.copySelectedTemplate.form.templateName = ''
    },
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value.length

      // name
      if (field == 'name') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 20
        if (strLength > 20) {
          return callback(new Error(`文字超长 ${strLength} / 20`))
        }
      }
      // descDetails
      if (field == 'descDetails') {
        //  长度最大为 3000
        if (strLength > 3000) {
          return callback(new Error(`文字超长 ${strLength} / 3000`))
        }
      }

      // title
      if (field == 'title') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 300
        if (strLength > 300) {
          return callback(new Error(`文字超长 ${strLength} / 300`))
        }
      }

      // 五点描述 长度最大为 500
      if (field == 'desc1' || field == 'desc2' || field == 'desc3' || field == 'desc4' || field == 'desc5') {
        // 五点描述 长度最大为 500
        if (strLength > 500) {
          return callback(new Error(`文字超长 ${strLength} / 500`))
        }
      }
      return callback()
    },

    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
      this.form.skuId = this.skuId
    },
    // 验证数据是否改变
    validFormData() {
      let flag = null
      if (JSON.stringify(this.backFormDate) == JSON.stringify(this.form)) {
        flag = false
      } else {
        flag = true
      }

      return flag
    },

    handleAddTemplate() {
      this.resetForm()
      this.type = 'add'
      this.selectedTemplate = ''
    },
    deleteTemplate() {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deleteTemplate(this.selectedTemplate).then((res) => {
          if (res.code == 200) {
            this.$message({ type: 'success', message: res.msg })
            this.getList()
          }
        })
      })
    },
    setTemplateInfo(id, flag = false) {
      this.resetForm()
      const info = this.templateList.filter((item) => item.id == id || item.name == id)[0] || {}
      this.selectedTemplate = info.id
      Object.keys(this.form).forEach((key) => {
        const _data = JSON.parse(JSON.stringify(info))
        if (key == 'distributorSkuTemplateImgList') {
          this.form[key] = _data[key]?.map((i) => i.templateImgUrl)?.toString()
        } else {
          this.form[key] = _data[key] ? _data[key] : ''
        }
      })
      if (flag) {
        this.backFormDate = JSON.parse(JSON.stringify(this.form))
      }
      this.type = 'edit'
    },
    addTemplate() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            skuId: this.skuId,
            distributorSkuTemplateImgList: this.form.distributorSkuTemplateImgList?.split(',')?.map((item, index) => {
              return {
                templateImgUrl: item,
                sort: index + 1,
              }
            }),
          }
          addTemplate(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(true, templateName)
              this.type = ''
            }
          })
        }
      })
    },
    handleEdit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            skuId: this.skuId,
            distributorSkuTemplateImgList: this.form.distributorSkuTemplateImgList?.split(',')?.map((item, index) => {
              return {
                distrId: this.form.distrId,
                skuTemplateId: this.selectedTemplate,
                templateImgUrl: item,
                sort: index + 1,
              }
            }),
          }
          editTemplate(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(true, templateName)
              this.type = ''
            }
          })
        }
      })
    },
    getList(flag = false, templateName = null) {
      getTemplateList(this.skuId).then((res) => {
        const { distributorSkuTemplateList, imgUrl, skuNo, stockPositionNo } = res.data
        if (flag && this.$parent?.$parent?.updateSkuImg) {
          this.$parent?.$parent?.updateSkuImg(imgUrl)
        }
        /***************************头部信息******************************/
        this.info.skuNo = skuNo
        this.info.stockPositionNo = stockPositionNo
        /***************************头部信息******************************/
        this.templateList = distributorSkuTemplateList || []
        /***************************设置相关信息******************************/
        if (templateName) {
          this.setTemplateInfo(templateName, flag)
        } else {
          this.setTemplateInfo(this.templateList[0]?.id, flag)
        }
        /***************************设置相关信息******************************/

        if (this.templateList.length == 0) {
          this.type = ''
        }
      })
    },
    submitForm() {},
    cancel() {
      // this.$parent.$parent.cancel()
      this.$emit('cancel')
    },
  },
}
</script>

<style lang="scss" scoped>
.des-desc5 {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border: 1px solid #e1dddd;
  border-bottom: none;
}

.des-detail {
  display: flex;
  height: 265px;
  border: 1px solid #e1dddd;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.template-img {
  display: flex;
  overflow: auto;
  overflow-y: hidden;
  border: 1px solid #e1dddd;
  border-radius: 8px;
  padding: 5px;
}
</style>
